package br.com.foxinline.servico;

import br.com.foxinline.modelo.Vacina;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.Query;

/**
 *
 * @author laverson
 */
@Stateless
public class VacinaServico extends ServicoGenerico<Vacina> {

    public VacinaServico() {
        super(Vacina.class);
    }

    public List<Vacina> autoComplete(String query) {
        return findByName(query);
    }

    public List<Vacina> findByName(String query) {
        List<Vacina> results = getEntityManager().createQuery("select v from " + Vacina.class.getSimpleName() + " v where lower(v.nome) like '%" + query.toLowerCase().trim() + "%'").getResultList();
        return results;
    }

    public List<Vacina> autocomplete(String query, List<Vacina> vacinas) {

        if (vacinas.isEmpty()) {
            return autoComplete(query);
        }

        String vacinasId = "(";

        for (int i = 0; i < vacinas.size(); i++) {
            vacinasId += vacinas.get(i).getId();
            if (i != vacinas.size() - 1) {
                vacinasId += ",";
            }
        }

        vacinasId += ")";

        String sql = "select v from " + Vacina.class.getSimpleName() + " v "
                + "   where lower(v.nome) like '%" + query.toLowerCase().trim() + "%'"
                + "   and v.id not in " + vacinasId;

        Query createQuery = getEntityManager().createQuery(sql);

        return createQuery.getResultList();
    }
}
